<?php

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use \EasyWeChat\Kernel\Support\XML;

/**
 * 微信被动回复消息处理
 * @package App\Jobs
 */
class WxmsgSendHandle implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    private $appid;
    private $content;
    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($appid, $content)
    {
        $this->appid = $appid;
        $this->content = $content;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        //判断是不是xml格式
        $xml_parser = xml_parser_create();
        if(!xml_parse($xml_parser, $this->content,true)){
            xml_parser_free($xml_parser);
            return false;
        }
        $message = XML::parse($this->content);
        if (!$message){
            return false;
        }
        $data = $message;
        unset($data['ToUserName'], $data['FromUserName'], $data['MsgType'], $data['CreateTime']);
        return \App\Models\WxmsgSend::updateOrCreate(
            ['appid' => $this->appid, 'to_user_name'=>$message['ToUserName'] ?? '', 'create_time'=>$message['CreateTime'] ?? time()],
            ['msg_type'=>$message['MsgType'] ?? '', 'from_user_name'=>$message['FromUserName'] ?? '','data'=>$data]
        );
    }
}
